import createDOMElement from './createDOMElement'
import createElement from './createElement'
import mountElement from './mountElement'
import updateNodeElement from './updateNodeElement'

export default function diff(virtualDOM, container, oldDOM) {
    const oldVirtualDOM = oldDOM && oldDOM._virtualDOM

    if (!oldDOM) {
        mountElement(virtualDOM, container)
    } else if (oldVirtualDOM && oldVirtualDOM.type !== virtualDOM.type && typeof virtualDOM.type !== "function") {
        // 新舊節點類型不同而且不是組件的情況
        const newElement = createDOMElement(virtualDOM)
        // 直接取代
        oldDOM.parentNode.replaceChild(newElement, oldDOM)
    } else if (oldVirtualDOM && oldVirtualDOM.type === virtualDOM.type) {
        if (virtualDOM.type === "text") {
            // 更新文本節點
            updateTextNode(virtualDOM, oldVirtualDOM, oldDOM)
        } else {
            // 更新元素節點
            updateNodeElement(oldDOM, virtualDOM, oldVirtualDOM)
        }
    }

    virtualDOM.children.forEach((child, i) => {
        diff(child, oldDOM, oldDOM.childNodes[i])
    })

    // 刪除多餘節點
    // 获取就节点的数量
    let oldChildNodes = oldDOM.childNodes
    // 如果旧节点的数量多于要渲染的新节点的长度
    if (oldChildNodes.length > virtualDOM.children.length) {
        for (
            let i = oldChildNodes.length - 1;
            i > virtualDOM.children.length - 1;
            i--
        ) {
            unmountNode(oldChildNodes[i])
        }
    }
}